import React, { Component } from 'react';
import {
  StyleSheet,
  View,
  DeviceEventEmitter,
  TextInput,
  TouchableOpacity,
  FlatList,
} from 'react-native';
import {
  Text,
  Container,
  Header,
  Left,
  Body,
  Right,
  Title,
  Item,
  List,
  ListItem,
  Thumbnail,
  Button,
  Icon,
  Image,
  Badge,
  ActionSheet,
} from 'native-base';
import theme from '../../../native-base-theme/variables/commonColor';
import ZlstIcon from '../../../components/zlst-icons';
import { Loading, BlankBackground, ListFooter, } from '../../../components';
import * as incidentRequest from '../../../services/incidentRequest';
import { produce } from 'immer';

const BUTTONS = ['所有', '待接收', '维修中', '待验收', '验收关闭', '带遗留问题关闭', '取消'];
const DESTRUCTIVE_INDEX = 3;
const CANCEL_INDEX = 6;

class Search extends Component {
  inputValue = '';

  page = 1;

  rows = 6;

  status = '';

  statusName = '';

  condition = '';

  static navigationOptions = {
    header: null,
  }

  // 构造方法
  constructor(props) {
    super(props);
    this.state = {
      errorTag: false,
      isError: false,
      showLoading: false,
      refreshing: false,
      listData: [],
      total: 0,
      isMore: false,
      btnBack: false,
    };
  }

  componentDidMount() {
    // this.queryData();
    DeviceEventEmitter.addListener('refreshSearchPageEvent', this.refreshSearchPageEvent);
    if (this.props.navigation) { // 路由带入参数
      // console.log(this.props.navigation.state.params);
      this.setState({ btnBack: true });
      this.condition = this.props.navigation.state.params.code;
      this.queryData('refresh');
    } else {
      // this._onInitRefresh();
      this.swipeToSearchListhener = DeviceEventEmitter.addListener('swipeToSearch', this.queryInfoEvent);
    }
  }


  componentWillUnmount() {
    if (this.swipeToSearchListhener) {
      this.swipeToSearchListhener.remove();
    }
    DeviceEventEmitter.removeAllListeners('refreshSearchPageEvent');
  }

  queryInfoEvent = (v) => {
    if (this.state.listData.length === 0) {
      this._onInitRefresh();
    }
  }

  refreshSearchPageEvent = () => {
    this._onInitRefresh();
  }

  // 查询数据
  queryData = async (flag) => {
    // alert('22222')
    const ajaxData = {
      condition: this.condition,
      status: this.status,
      page: this.page,
      rows: this.rows,
      isEquipFlag: this.props.category === 'incident' ? 0 : 1,
    };
    try {
      if (flag === 'search') {
        DeviceEventEmitter.emit('showLoading', true);
      }
      // console.log('===', ajaxData);
      // if (flag === 'refresh') {
      //   this.setState({ refreshing: true });
      // }
      const list = await incidentRequest.getFindToSearch(ajaxData);
      this.setState(produce(draft => {
        if (flag === 'refresh' || flag === 'search') {
          draft.listData = list.data;
        } else {
          draft.listData = draft.listData.concat(list.data);
        }
        draft.refreshing = false;
        draft.isMore = draft.listData.length < list.totalNum;
        draft.total = list.totalNum;
        DeviceEventEmitter.emit('showLoading', false);
      }));
    } catch (error) {
      this.setState({ isError: true, refreshing: false });
      DeviceEventEmitter.emit('showLoading', false);
    }
  }

  // 搜索
  _onSearch = () => {
    // alert(this.inputValue);
    this.condition = this.inputValue;
    // this.status = '';
    // 关闭软键盘
    this.page = 1;
    TextInput.State.blurTextInput(TextInput.State.currentlyFocusedField());
    this.queryData('search');
  };

  tolist = () => {
    DeviceEventEmitter.emit('swiperIncidentPageEvent', 1);
  };

  _onChangeText = v => {
    this.inputValue = v;
  };

  // 刷新时候获取数据
  _onRefresh = () => {
    this.page = 1;
    this.queryData('refresh');
  }

  // 上拉加载数据
  _onEndReached = () => {
    if (this.state.isMore) {
      this.page = this.page + 1;
      this.queryData('load');
    }
  }

  // 列表上拉加载没有数据时
  _renderListFooter = () => (
    (this.state.listData.length > 0) && <ListFooter isMore={this.state.isMore} />
  );

  // 错误页面刷新方法
  _onInitRefresh = () => {
    this.page = 1;
    this.queryData('search');
  }

  // 显示图片
  _showDetaiImage = (item) => {
    // console.log('URL====', incidentRequest.getDownloadImg);
    if (item.failurePic) {
      return {
        uri: `${incidentRequest.getDownloadImg}/${item.failurePic}?token=${global.__TOKEN_ACCESS__}`,
      };
    }
    return require('../../../../assets/images/no-pic.png');
  }

  // 每一行
  renderRow = (item) => {
    // -1：草稿；01：撤销；02：草稿关闭；03：验收关闭；04：带遗留问题关闭；10：待接收；20：已接收；30：维修完成；
    let dotColor = '';
    switch (item.item.failureStatus) {
      case '10':
        dotColor = 'red';
        break;

      case '20':
        dotColor = '#19be6b';
        break;

      case '30':
        dotColor = '#2d8cf0';
        break;

      default:
        dotColor = '#2d8cf0';
        break;
    }
    return (
      <TouchableOpacity>
        <View style={{ backgroundColor: '#ffffff', borderRadius: 8, marginLeft: 8, marginRight: 8, marginBottom: 8, padding: 8 }}>
          <View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
            <View style={{ flexDirection: 'row', alignItems: 'center' }}>
              <View style={[styles.circle, { backgroundColor: dotColor }]} />
              <Text style={styles.odd} note numberOfLines={1}>{this.props.category === 'incident' ? '故障单号' : '隐患单号'}:{item.item.failureCode}</Text>
            </View>
            <View>
              <Text style={styles.time} note numberOfLines={1}>申报时间:{item.item.declareTime && item.item.declareTime.length > 11 && item.item.declareTime.substring(11, item.item.declareTime.length)}</Text>
            </View>
          </View>
          <List>
            <ListItem onPress={() => this.cellAction(item)} thumbnail>
              <Left>
                <Thumbnail
                  style={{ backgroundColor: 'black', width: 80, height: 80, borderRadius: 4, marginTop: 4, marginLeft: 0 }}
                  square
                  source={this._showDetaiImage(item.item)}
                />
              </Left>
              <Body style={{ borderBottomWidth: 0, paddingTop: 0, paddingBottom: 0 }}>
                <View style={{ flexDirection: 'row', alignItems: 'center', flex: 1 }}>
                  <View style={{ flex: 1, flexDirection: 'row', alignItems: 'center' }}>
                    <Text style={{ fontSize: 15, color: theme.myPrimary }}>名称</Text>
                  </View>
                  <View style={{ flex: 4, alignItems: 'center', flexDirection: 'row' }}>
                    <Text note style={{ flex: 4, flexWrap: 'wrap', fontSize: 15 }} numberOfLines={1}>{this.props.category === 'incident' ? item.item.equipmentName : item.item.facilityName}</Text>
                    <View style={{ flex: 1, justifyContent: 'flex-end', flexDirection: 'row' }}>
                      <Badge style={styles.badge}>
                        <Text style={{ color: '#2d8cf0', fontSize: 12 }}>{item.item.failureLevelDesc}</Text>
                      </Badge>
                    </View>
                  </View>
                </View>
                <View style={{ flex: 1, flexDirection: 'row', alignItems: 'center' }}>
                  <View style={{ flex: 1 }}>
                    <Text style={{ fontSize: 15, color: theme.myPrimary }}>现象</Text>
                  </View>
                  <View style={{ flex: 4 }}>
                    <Text note style={{ fontSize: 15 }} numberOfLines={1}>{item.item.failureDesc} {item.item.failureKeywords}</Text>
                  </View>
                </View>
                <View style={{ flex: 1, flexDirection: 'row', alignItems: 'center' }}>
                  <View style={{ flex: 1, flexDirection: 'row', alignItems: 'center'}}>
                    <Text style={{ flex: 1, fontSize: 15, color: theme.myPrimary }}>状态</Text>
                  </View>
                  <View style={{ flex: 4, flexDirection: 'row', alignItems: 'center'}}>
                    <Text note style={{ flex: 4, fontSize: 15 }} numberOfLines={1}>{item.item.failureStatusDesc}</Text>
                  </View>
                </View>
              </Body>
            </ListItem>
          </List>
        </View>
      </TouchableOpacity>
    );
  };

  // 点击某行
  cellAction = (item)=> {
    // failureId
    // console.log('==', item);
    const par = {
      fromNavigation: true,
      id: item.item.failureId,
      code: item.item.failureCode,
    };
    global.navigation.navigate({ routeName: 'Info', params: par });
    // DeviceEventEmitter.emit('swipeToDetail', par);
  };

  // 状态选择
  _onState = () => {
    return (
      /**
       * title 标题
       * options 里面的数组的内容，最好是字符串
       * cancelButtonIndex 取消按钮的索引，在options
       * destructiveButtonIndex 删除按钮的索引，在options ， 加红色的按钮
       * onPress 当点击选项的时候调用，同时传递给我们被点击的索引
       * tintColor 选项的颜色
       */
      ActionSheet.show(
        {
          options: BUTTONS,
          cancelButtonIndex: CANCEL_INDEX,
          // destructiveButtonIndex: DESTRUCTIVE_INDEX,
          // title: 'Testing ActionSheet',
        },
        buttonIndex => {
          switch (buttonIndex) {
            case 0:
              this.status = '';
              this.statusName = BUTTONS[0].toString();
              break;
            case 1:
              this.status = '10';
              this.statusName = BUTTONS[1].toString();
              break;
            case 2:
              this.status = '20';
              this.statusName = BUTTONS[2].toString();
              break;
            case 3:
              this.status = '30';
              this.statusName = BUTTONS[3].toString();
              break;
            case 4:
              this.status = '03';
              this.statusName = BUTTONS[4].toString();
              break;
            case 5:
              this.status = '04';
              this.statusName = BUTTONS[5].toString();
              break;
            default:
              break;
          }
          if (buttonIndex !== 6) {
            this.condition = this.inputValue;
            this.page = 1;
            this.queryData('search');
          }
        },
      )
    );
  }

  // 点击返回按钮
  _toMianPage = () => {
    if (this.props.navigation) {
      this.props.navigation.goBack();
    }
  }

  render() {
    const { errorTag, listData, showLoading, isError, refreshing, btnBack } = this.state;
    let FlatListHtml;
    let returnBtn;
    if (listData.length === 0) {
      FlatListHtml = <BlankBackground isError={isError} onRefresh={this._onInitRefresh} />;
    } else {
      FlatListHtml = (
        <FlatList
          data={listData}
          renderItem={item => this.renderRow(item)}
          keyExtractor={(item, index) => item + index}
          onRefresh={this._onRefresh}
          refreshing={refreshing}
          onEndReachedThreshold={0.05}
          scrollEventThrottle={200}
          onEndReached={this._onEndReached}
          ListFooterComponent={this._renderListFooter}
        />
      );
    }
    // 是否显示返回按钮
    if (btnBack) {
      returnBtn = (<ZlstIcon
        onPress={this._toMianPage}
        style={styles.backIcon}
        name="fanhui"
        size={20}
        color={fontColor}
      />
      );
    }

    let statusHtml;
    // 显示所选状态
    if (this.statusName !== '') {
      statusHtml = (<Text style={{ color: '#ffffff', fontSize: 12, paddingTop: 6 }}>（{this.statusName} {this.state.total}）</Text>);
    }
    return (
      <Container style={styles.container}>
        <Header style={{ paddingTop: 0 }}>
          <Left>
           { returnBtn }
          </Left>
          <Body style={{ alignItems: 'center' }}>
            <TouchableOpacity onPress={this._onState}>
              <View style={{ flexDirection: 'row', display: 'flex' }}>
                <Title>{this.props.category === 'incident' ? '故障查询' : '隐患查询'}</Title>
                <Icon style={{ color: '#ffffff' }} type="MaterialIcons" name="expand-more" />
                { statusHtml }
              </View>
            </TouchableOpacity>
          </Body>
          <Right>
          </Right>
        </Header>
        <Item style={styles.circle_container}>
          <Icon name="ios-search" style={styles.ios_search} />
          <TextInput
            style={styles.text_input}
            underlineColorAndroid="transparent"
            placeholder="设备编号/设备名称/单号/现象"
            onChangeText={this._onChangeText}
            onSubmitEditing={this._onSearch}
          />
          <TouchableOpacity style={{ padding: 10 }} onPress={this._onSearch}>
            <Text style={{ color: '#0391ff', fontSize: 14 }}>搜索</Text>
          </TouchableOpacity>
        </Item>
        {FlatListHtml}
      </Container>
    );
  }
}
const fontColor = '#ffffff';
const styles = StyleSheet.create({
  container: {
    width: '100%',
    flex: 1,
    backgroundColor: theme.myPrimary,
  },
  Header: {
    width: '100%',
  },
  circle_container: {
    height: 40,
    borderRadius: 4,
    borderBottomWidth: 0,
    marginBottom: 8,
    marginLeft: 8,
    marginRight: 8,
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: 'white',
  },
  text_input: {
    flex: 1,
    marginLeft: 5,
    padding: 0,
    backgroundColor: 'white',
  },
  Text: {
    // backgroundColor: theme.myPrimary,
    // color: '#ffffff',
    fontSize: 15,
  },
  badge: {
    borderWidth: 1,
    borderColor: '#2d8cf0',
    backgroundColor: '#ffffff',
    height: 20,
  },
  odd: {
    // backgroundColor: theme.myPrimary,
    // color: '#ffffff',
    fontSize: 12,
  },
  time: {
    // backgroundColor: theme.myPrimary,
    // color: '#ffffff',
    fontSize: 12,
  },
  circle: {
    height: 10,
    width: 10,
    borderRadius: 5,
    marginRight: 5,
  },
  ios_search: {
    fontSize: 24,
    paddingLeft: 6,
    color: '#686868',
  },
  backIcon: {
    width: 24,
  },
});

export default Search;
